package com.smart.jetpackcomposestate.examples

import android.os.Bundle
import android.text.Editable
import android.util.Log
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doAfterTextChanged
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.smart.jetpackcomposestate.R
import com.smart.jetpackcomposestate.databinding.ActivityHelloComposeStateBinding

/**
 * @author huangzehui
 * @date 2025/8/6 13:04 周三
 * @description
 *
 * 30 - 单向数据流
 * https://www.bilibili.com/video/BV1ob4y1a7ad?spm_id_from=333.788.player.switch&vd_source=e07cc8cc94eb22bd76722071b03cd199&p=30
 */
class HelloComposeStateWithViewModelActivity : AppCompatActivity() {

    private val binding by lazy {
        ActivityHelloComposeStateBinding.inflate(layoutInflater)
    }

    private val helloViewModel by viewModels<HelloViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        setTheme(R.style.Theme_DN_Compose_Learn1)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.etText.doAfterTextChanged { text: Editable? ->
            helloViewModel.onNameChange(text?.toString() ?: "")
        }

        helloViewModel.name.observe(this) { name ->
            binding.tvText.text = "Hello, ${name}"
        }

    }


    class HelloViewModel : ViewModel() {
        private val _name = MutableLiveData("")
        val name: LiveData<String> = _name

        fun onNameChange(newName: String) {
            _name.value = newName
        }
    }

}